import { message } from 'antd';
import axios from 'axios'

const Ajax = {}

const axiosInstance = axios.create({
    baseURL: "/api",
    timeout: 5000,
})

axiosInstance.interceptors.request.use(function (config) {
    config.headers['X-ACCESS-TOKEN'] = sessionStorage.getItem("user_token") || ''
    return config;
}, function (error) {
    return Promise.reject(error);
});

/**
 * 相应拦截，拦截401
 */
axiosInstance.interceptors.response.use(resp=>{
    if(resp && resp.status===200){
        return resp.data
    }
},(error='') => {
    if(error && error.response) {
        let httpStatus = error.response.status
        if(httpStatus===401) {
            window.location.href="/"
            return
        }
    }
    message.error(error.message);
    console && console.log(error)
    return {}
})

Ajax.json = async (url, params) => {
    return await axiosInstance({
        method: 'post',
        url: url,
        data: params || {},
        header:{
            'Content-Type':'application/json',
        }
    });
}

Ajax.post = async (url, params) => {
    return await axiosInstance({
        method: 'post',
        url: url,
        params: params || {},
        header:{
            'Content-Type': 'application/x-www-form-urlencoded',
        }
    });
}

export default Ajax